//
//  YBTraveldetialViewController.m
//  OurTourism
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//

#import "YBTraveldetialViewController.h"
#import "YBTraveldetialTableViewCell.h"
#import "YBTravelUserdownTableViewCell.h"
#import "MapViewController.h"
#import "MZRecommendThirdViewController.h"
#import "MZRecommendModel.h"
#import "MZRecommendPhotosViewController.h"
#import "ybPhotoCollectionViewCell.h"
#import "MZPhotoModel.h"


@interface YBTraveldetialViewController ()<UITableViewDataSource, UITableViewDelegate,jumpToLocationPage,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)YBDestinationModel *noteModel; //包含所有信息的model

@property (nonatomic, retain)YBDestinationModel *userModel;
@property (nonatomic, retain)NSMutableArray *modelDayArr; //保存游记具体内容总数据
@property (nonatomic, retain)NSMutableArray *modelWaypointsArr; //保存每天waypoints套对象的数组

@property (nonatomic, retain)NSMutableArray *modelLocationArr;  //保存每天的location对象

@property (nonatomic, strong)MBProgressHUD *hud;

@property (nonatomic, strong)NSMutableArray *indexArr;

@property (nonatomic, strong)NSMutableArray *photoArr;


@end

@implementation YBTraveldetialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    //[self addScreenEdgePan];
    

      [self loadMBProgress];
       [self getData];



    
    
}
// 小菊花
- (void)loadMBProgress
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    self.hud.dimBackground = NO;
    //设置对话框文字
    self.hud.labelText = @"loading";
    self.hud.minShowTime = 50;
    self.hud.activityIndicatorColor = [UIColor whiteColor];
    self.hud.labelColor = [UIColor whiteColor];
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(1);
    } completionBlock:^{
        //操作执行完后取消对话框
        [self.hud removeFromSuperview];
        self.hud = nil;
    }];
    
}
- (void)getData
{
        NSString *url = nil;
    if (self.locationImpressionToDetailID != nil) {
        url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@", self.locationImpressionToDetailID];
        
    }
    
    else{
      url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@", self.valueId];
    
    }

//    //判断从哪个界面跳转过来 从哪个数据里取id
   
    
    [MZNetHandle  getUrl:url cookie:nil result:^(id result) {
        NSMutableDictionary *tempDic = result;
        self.noteModel = [[YBDestinationModel alloc]init];
        [self.noteModel setValuesForKeysWithDictionary:tempDic]; //把当前字典转化成对象  包含所有信息
        self.userModel = [[YBDestinationModel alloc]init];
        [self.userModel setValuesForKeysWithDictionary:result[@"user"]]; //用户信息model
        self.modelDayArr = [YBDestinationModel transformWithArray:tempDic[@"days"]];  //保存游记具体内容总数据
        NSMutableArray *waypointsArr = [NSMutableArray array]; //保存所有waypoints数组
        self.modelLocationArr = [NSMutableArray array];  //保存所有location的 model对象
        for (NSDictionary *dic in tempDic[@"days"]) {
            
            NSMutableArray *tempWaypointArr = [NSMutableArray array];
            for (NSMutableDictionary *dic2 in dic[@"waypoints"]) {
                if (dic2[@"id"] != nil) //有的waypoints字典里并没有数据
                {
                    [tempWaypointArr addObject:dic2];
                }
            }
            [waypointsArr addObject:tempWaypointArr]; //数组套数组套waypoints对象
            NSMutableArray *tempArr = [NSMutableArray array];  //用来保存每天的waypoint里的location对象
            //遍历每天得waypoint数组
            for (NSMutableDictionary *dic in tempWaypointArr)
            {
                if ([dic[@"location"] class] == [NSNull class]) {
                    YBDestinationModel *model = [[YBDestinationModel alloc]init];
                    [tempArr addObject:model];
                }else{
                    //保存location对象
                    YBDestinationModel *model = [[YBDestinationModel alloc]init];
                    [model setValuesForKeysWithDictionary: dic[@"location"]];
                    [tempArr addObject:model];
                }
            }
            [self.modelLocationArr addObject:tempArr];
        }
        self.modelWaypointsArr = [NSMutableArray array];
        for (NSMutableArray *arr in waypointsArr) {
            [self.modelWaypointsArr addObject: [YBDestinationModel transformWithArray:arr]];
            [self.indexArr addObjectsFromArray:arr];
        }
        [self.hud removeFromSuperview];
        [self createTableView];
        [self creatCollection];
        
    }];
    
}

#pragma mark - 按钮触发方法
- (void)backToLast:(NSString *)nnn;
{
    if([self.whoPush isEqualToString:@"mz"]){
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }else{
    
    [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    [self.view addSubview:self.tableView];
   
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(20, 20, 40, 40);
    [btn setImage:[UIImage imageNamed:@"iconfont-iconfonticonfontjiantouzuo11@2x"] forState:0];
    [btn addTarget:self action:@selector(backToLast:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:btn];
    
    //基类方法 改变为夜间模式颜色
  //  [[self class]BoolIsNight:self.tableView];
    
    
}




#pragma mark - 游记详情 location跳转下一页 button协议方法
- (void)jumpToLocation:(NSIndexPath *)indexpath
{
    
    
    
    if ([self.modelLocationArr[indexpath.section - 1][indexpath.row] longitude] && ![self.modelWaypointsArr[indexpath.section - 1][indexpath.row]poiName]) {
        
        MapViewController *map = [[MapViewController alloc]init];
        map.locationModel = self.modelLocationArr[indexpath.section - 1][indexpath.row];
        map.modelWayPoints = self.modelWaypointsArr[indexpath.section - 1][indexpath.row];
        [self presentViewController:self animated:YES completion:^{
            
        }];
       
        
    }
    else
    {

//        MZRecommendThirdViewController *pageView = [[MZRecommendThirdViewController alloc]init];
//        pageView.tempModel = self.modelWaypointsArr[indexpath.section - 1][indexpath.row];
//        
//        [self.navigationController pushViewController:pageView animated:YES];

//        MZRecommendThirdViewController *pageView = [[MZRecommendThirdViewController alloc]init];
////        pageView.tempModel = self.modelWaypointsArr[indexpath.section - 1][indexpath.row];
//        pageView.tempDic = [self.indexArr[indexpath.section - 1] dataValue][indexpath.row];
//        NSLog(@"%@", pageView.tempDic);
//        [self.navigationController pushViewController:pageView animated:YES];

        NSLog(@"连接没有");
       
    }
    
    
}


#pragma mark - tableView分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.modelWaypointsArr.count + 1;
}

#pragma mark - tableView分区头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else{
        return 20;
    }
}
#pragma mark - tableView头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    else{
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 20)];
        view.backgroundColor  = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        UIView *viewCircle = [[UIView alloc]initWithFrame:CGRectMake(20, -20, 20, 20)];
        viewCircle.layer.masksToBounds = YES;
        viewCircle.layer.cornerRadius = 10;
        viewCircle.backgroundColor = [UIColor colorWithRed:0.89 green:0.87 blue:0.78 alpha:1];
        [view addSubview:viewCircle];
        
        UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(28, viewCircle.frame.size.height + viewCircle.frame.origin.y, 5, 20)];
        viewLine.backgroundColor = [UIColor colorWithRed:0.89 green:0.87 blue:0.78 alpha:1];
        [view addSubview:viewLine];
        UILabel *labelDay = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, 50, 12)];
        labelDay.textColor = [UIColor colorWithRed:0.79 green:0.73 blue:0.6 alpha:1];
        labelDay.font = [UIFont systemFontOfSize:15];
        [view addSubview:labelDay];
       
        
        UILabel *labelDate = [[UILabel alloc]initWithFrame:CGRectMake(110, 0, 150, 12)];
        labelDate.textColor = [UIColor colorWithRed:0.79 green:0.73 blue:0.6 alpha:1];
        labelDate.font = [UIFont systemFontOfSize:15];
        [view addSubview:labelDate];
       
        
        NSNumber *day =  ((YBDestinationModel *) self.modelDayArr[section - 1]).day;
        labelDay.text = [NSString stringWithFormat:@"%@%@%@", @"第", day, @"天"];
        
        NSString *date = ((YBDestinationModel *) self.modelDayArr[section - 1]).date;
        labelDate.text = [date substringFromIndex:5];
        
        
        return view;
    }
}

#pragma mark - tableView行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else
    {
        return [self.modelWaypointsArr[section - 1] count];
    }
}
#pragma mark - tableView Cell赋值

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        YBTraveldetialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"user"];
        if (!cell) {
            cell = [[YBTraveldetialTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"user"];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.modelUser = self.userModel;
        cell.modelNotes = self.noteModel;
        return cell;
    }
    else{
        YBTravelUserdownTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"note"];
        if (!cell) {
            cell = [[YBTravelUserdownTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"note"];
        }
        //向cell传递indexpath 因为数据在当前页 协议点击方法需要数据的位置  又取不到section  和 row  所以需要传递进去  而不能在当前页传递是因为一次可能会出现多个cell  数据不准
        cell.indexpath = indexPath;
            //判断是是否有跳到地点详情的url是否有type
        //  cell.type = self.modelWaypointsArr
        cell.delegate = self; // location按钮代理人为当前controller
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.modelTravelNotes = self.noteModel;
        cell.modelUser = self.userModel;
        cell.modelWaypoint = self.modelWaypointsArr[indexPath.section - 1][indexPath.row];
        return cell;
    }
}



#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 60 + (self.view.frame.size.width - 20) / 8 + 10 + 10 + 30 + 50 + 20;
    }
    else{
        YBDestinationModel *tempModel = self.modelWaypointsArr[indexPath.section - 1][indexPath.row];
        CGFloat imgH = (tempModel.h).integerValue;
        CGFloat imgW = (tempModel.w).integerValue;
        CGFloat h = [[self class]heightWithText:tempModel.text fontSize:15 Width:WIDTH - 40];
        // imgH * WIDTH / imgW + 10 + h + 10 + 15 + 10 白色背景图高度
        if (imgH!=0 && imgW != 0) {
            return imgH * WIDTH / imgW + 10 + h + 10 + 15 + 10 + 20;
        }
        else
        {
            return 10 + h + 10 + 15 + 10 + 20;
        }
    }
}


//计算文本高度的方法
+ (CGFloat)heightWithText:(NSString *)text fontSize:(CGFloat)fontsize Width:(CGFloat)width

{
    //设置一个字典 保存文本属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]};
    
    //预设尺寸 文本最大不会超过这个范围
    CGSize size = CGSizeMake(width, 2000);
    //根据文本信息 计算得到一个CGRect
    //参数1. 尺寸范围
    //参数2. 获取文本尺寸的方式
    //参数3. 文本属性
    //参数4. 无用信息(上下文)
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

#pragma mark - tableView选中方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
//    [UIView animateWithDuration:0.3 animations:^{
//        [self.tableView removeFromSuperview];
//        self.collectionView.alpha = 1;
//        [self.view addSubview: self.collectionView];
//    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
}


- (void)creatCollection
{
    UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //列间距
    layout.minimumInteritemSpacing = 0;
    //行间距
    layout.minimumLineSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.itemSize =CGSizeMake(WIDTH, HEIGTH);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGTH) collectionViewLayout:layout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.collectionView];
    self.collectionView.alpha = 0;
    [self.collectionView registerClass:[ybPhotoCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ybPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.tempModel = self.modelWaypointsArr[indexPath.section +1][indexPath.item];
    return cell;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSLog(@"%ld",self.modelWaypointsArr.count);
    return self.modelWaypointsArr.count;
  
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.modelWaypointsArr.count + 1;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
